/**
 * Copyright (c) 2015-2020, wss 王山山
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wss.utils;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import com.wss.utils.exception.JsEngineException;

/**
 * JS工具类
 * @author wss
 *
 */
public class JsEngineUtil {
	/*
	 * 获取JS引擎
	 */
	private static final ScriptEngine ENGINE = new ScriptEngineManager().getEngineByName("js");
	/*
	 * 获取类的根路径 
	 */
	private static final String ROOT_PATH = JsEngineUtil.class.getClassLoader().getResource("").getFile();
	
	/**
	 * 执行指定的js文件，并返回结果
	 * 
	 * @param filePath		js文件路径
	 * @return				返回脚本执行结果
	 */
	public static Object eval(String filePath) {
		String absolutePath = ROOT_PATH + File.separator + filePath;
		try (
			Reader reader = new FileReader(absolutePath);
		) {
			return ENGINE.eval(reader);
		} catch (IOException | ScriptException e) {
			throw new JsEngineException(e);
		}
	}
}
